package com.xnf.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnf.article.feigh.BehaviorFeign;
import com.xnf.article.mapper.ApCollectionMapper;
import com.xnf.article.service.ApCollectionService;
import com.xnf.model.article.dtos.CollectionBehaviorDto;
import com.xnf.model.article.pojos.ApCollection;
import com.xnf.model.behavior.dtos.BehaviorEntryDto;
import com.xnf.model.behavior.pojos.ApBehaviorEntry;
import com.xnf.model.common.dtos.ResponseResult;
import com.xnf.model.common.enums.AppHttpCodeEnum;
import com.xnf.model.user.pojos.ApUser;
import com.xnf.utils.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by xnf on 2022/3/8.
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper,ApCollection> implements ApCollectionService {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        System.out.println("collect service");
        if(dto == null || dto.getOperation() < 0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtils.get();
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        BehaviorEntryDto behaviorEntryDto = new BehaviorEntryDto();
        behaviorEntryDto.setUserId(apUser.getId());
        System.out.println("collect service " + apUser.getId());
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEntryId(apUser.getId(),0L);
        if (apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getEntryId, apBehaviorEntry.getEntryId())
                .eq(ApCollection::getArticleId, dto.getEntryId()));
        if(apCollection == null && dto.getOperation() == 0){
            apCollection = new ApCollection();
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setEntryId(apBehaviorEntry.getEntryId());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(dto.getPublishedTime());
            apCollection.setType(dto.getType());
            save(apCollection);
        }else{
            removeById(apCollection);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
